#!/usr/bin/env bash

# Define those global variables
if [ -f ./variables.sh ]; then
  source ./variables.sh
elif [ -f /scripts/variables.sh ]; then
  source /scripts/variables.sh
else
  echo "Cannot find the variables.sh files, pls check"
  exit 1
fi

cd /tmp/${CHANNEL_ARTIFACTS}

echo "Generate genesis block of system channel using configtx.yaml"
[ ! -f ${ORDERER0_GENESIS_BLOCK} ] &&
  configtxgen \
    -configPath /tmp \
    -channelID ${SYS_CHANNEL} \
    -profile ${ORDERER_GENESIS_PROFILE} \
    -outputBlock ${ORDERER0_GENESIS_BLOCK}
[ ! -f ${ORDERER0_GENESIS_BLOCK} ] && echo "Fail to generate genesis block ${ORDERER0_GENESIS_BLOCK}" && exit 1


echo "Create the new app channel ${APP_CHANNEL} tx using configtx.yaml"
[ ! -f ${APP_CHANNEL_TX} ] &&
  configtxgen \
    -configPath /tmp \
    -profile ${APP_CHANNEL_PROFILE} \
    -channelID ${APP_CHANNEL} \
    -outputCreateChannelTx ${APP_CHANNEL_TX}
[ ! -f ${APP_CHANNEL_TX} ] && echo "Fail to generate app channel tx file" && exit 1
#done

[ ! -f ${APP_CHANNEL_TX}.json ] &&
  configtxgen \
    -inspectChannelCreateTx ${APP_CHANNEL_TX} >${APP_CHANNEL_TX}.json

echo "Create the anchor peer configuration tx"
[ ! -f ${UPDATE_ANCHOR_ORG1_TX} ] &&
  configtxgen \
    -configPath /tmp \
    -profile ${APP_CHANNEL_PROFILE} \
    -channelID ${APP_CHANNEL} \
    -asOrg ${ORG1MSP} \
    -outputAnchorPeersUpdate ${UPDATE_ANCHOR_ORG1_TX}

[ ! -f ${UPDATE_ANCHOR_ORG1_TX} ] && echo "Fail to generate the anchor update tx for org1" && exit 1

echo "Output the json"
declare -a msps=("${ORG1MSP}")
for msp in "${msps[@]}"; do
  [ ! -f ${msp}.json ] &&
    configtxgen \
      -configPath /tmp \
      -printOrg ${msp} >${msp}.json
done
